package org.example.myleet.p649;

public class Solution {
    public String predictPartyVictory(String senate) {
        int[] position = new int[senate.length()];
        int i = 0;
        String result = end(position, senate);
        while (result.length() < 1) {
            //寻找下一个对手
            char s = senate.charAt(i);
            int j = i == senate.length()-1 ? 0 : i+1;
            while (position[j] < 0 || senate.charAt(j) == s) {
                if (j == senate.length()-1) {
                    j = 0;
                } else {
                    ++j;
                }
            }
            //沉默这个对手
            position[j] = -1;
            //检查是否结束
            result = end(position, senate);
            //寻找下一个没有被沉默的参议员
            if (i == senate.length()-1) {
                i = 0;
            } else {
                ++i;
            }
            while (result.length() < 1 && position[i] < 0) {
                ++i;
                if (i == senate.length()) {
                    i = 0;
                }
            }
        }
        return result.charAt(0) == 'D' ? "Dire" : "Radiant";
    }

    private String end(int[] position, String senate) {
        char c = 'A';
        for (int i=0; i<senate.length(); i++) {
            if (position[i] > -1) {
                if (c == 'A') {
                    c = senate.charAt(i);
                } else if (c != senate.charAt(i)) {
                    return "";
                }
            }
        }
        return c + "";
    }
}
